// 递归执行generator函数

export default () => {
  function ajax(url) {
    return new Promise(function (resolver, reject) {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.responseType = "json";
      xhr.onload = function () {
        if (this.status === 200) {
          resolver(this.response);
        } else {
          reject(new Error(this.statusText))
        }
      };

      xhr.send();
    })
  }



  function* main() {

    try {
      const users = yield ajax("/api/users.json");
      console.log(users);

      const requests = yield ajax("/api/posts.json");
      console.log(requests);

      const err = yield ajax("/api/user1.json");
    } catch (error) {
      console.log(error);
    }

  }
  function co(generator) {
    const g = generator();


    function handleResult(result) {
      if (result.done) return; // 生成器函数结束
      result.value.then(data => {
        handleResult(g.next(data))
      }).catch(err => {
        g.throw(err)
      })
    }

    handleResult(g.next())
  }

  co(main);
}